package com.xinpu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xinpu.entity.TUserSource;
import com.xinpu.service.ITUserSourceService;
import com.xinpu.service.OwnService;
import com.xinpu.vo.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * SourceController
 *
 * @author ayuan
 * @date 2021/4/16
 */
@RestController
@RequestMapping("/source")
public class SourceController {

    @Autowired
    private ITUserSourceService itUserSourceService;

    /**
     * 来源列表
     *
     * @return
     */
    @GetMapping("/list")
    public ResponseMessage list() {
        return ResponseMessage.ok(itUserSourceService.list());
    }

    /**
     * 创建或编辑来源
     *
     * @param map
     * @return
     */
    @PostMapping("/createOrEdit")
    public ResponseMessage createOrEdit(@RequestBody Map<String, String> map) {
        TUserSource tUserSource = new TUserSource();
        String id = map.get("id");
        String name = map.get("name");
        QueryWrapper<TUserSource> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        wrapper.eq("tenant_id", OwnService.getLoginer().getTenantId()).or().eq("tenant_id", "0");
        TUserSource userSource = itUserSourceService.getOne(wrapper);
        if (StringUtils.isNotBlank(id)) {
            tUserSource.setId(Integer.parseInt(id));
            if (userSource != null) {
                if (userSource.getId().toString().equals(id)) {
                    return ResponseMessage.error("客户来源已存在,请勿重复提交");
                }
            }
            tUserSource.setName(name);
            itUserSourceService.saveOrUpdate(tUserSource);
        }
        if (userSource == null) {
            tUserSource.setName(name);
            itUserSourceService.saveOrUpdate(tUserSource);
            return ResponseMessage.ok();
        }
        return ResponseMessage.ok("客户来源已存在,请勿重复提交");
    }

    /**
     * 删除来源
     *
     * @param map
     * @return
     */
    @PostMapping("/delete")
    public ResponseMessage delete(@RequestBody Map<String, String> map) {
        itUserSourceService.removeById(map.get("id"));
        return ResponseMessage.ok();
    }


}
